package com.holystone.splunk.app.controller;

import com.github.pagehelper.PageInfo;
import com.holystone.splunk.app.enums.AlertEnums;
import com.holystone.splunk.app.model.AlertVO;
import com.holystone.splunk.app.model.EventVO;
import com.holystone.splunk.app.mybatis.model.Alert;
import com.holystone.splunk.app.mybatis.model.Event;
import com.holystone.splunk.app.service.IIndexEventService;
import com.holystone.splunk.common.JSONMapper;
import com.holystone.splunk.common.PageData;
import com.holystone.splunk.common.SystemConstant;
import com.holystone.splunk.utils.DateFormatUtils;
import com.holystone.splunk.utils.JSONUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Set;

/**
 * Copyright (c) 2017, HOLYSTONE Technologies, Inc.
 * All right reserved.
 *
 * @author huyan
 * @date 2017/12/4
 * @desc:
 */
@Controller
@RequestMapping("/splunk/event")
public class EventController {

    private Logger logger = Logger.getLogger(this.getClass());
    private final String BASE_URL = "/splunk/event";
    @Resource(name = "indexEventService")
    private IIndexEventService indexEventService;
    /**
     * 初始化进入事件管理页面
     *
     * @return
     */
    @RequestMapping("/initEvent")
    public ModelAndView initEvent() {
        logger.debug(">>>>> 初始化进入事件管理页面");
        ModelAndView view = new ModelAndView(BASE_URL + "/event_list");
        try {
            List<String> nameList = indexEventService.getExistsEventSorts();
            view.addObject("nameList", nameList);
        } catch (Exception e) {
            logger.error("查询所有事件名称出错");
        }
        logger.debug("<<<<< 初始化进入事件管理页面");
        return view;
    }

    /**
     * 筛选出符合条件的告警信息分页
     *
     * @param pageNo
     * @param pageSize
     * @param conditions
     * @return
     */
    @ResponseBody
    @RequestMapping("/getEventByConditions")
    public ModelMap getEventByConditions(String pageNo, String pageSize, EventVO conditions) {
        logger.debug(">>>>> 获取事件分页 getEventByCondtions()");
        PageInfo<EventVO> info = null;
        try {
            info = indexEventService.getEventPageInfo(pageNo, pageSize, conditions);
            for (EventVO event : info.getList()) {
                event.setAlertCount(event.getAlerts().size());
            }
        } catch (Exception e) {
            logger.error("获取分页出错：" + e.getMessage(), e);
            return JSONMapper.createReturnMap(SystemConstant.RESPONSE_CODE_FAILURE, "获取事件分页出错", null, null);
        }
        logger.debug("<<<<< 获取事件分页 getEventByCondtions()");
        return PageData.getReturnMap(info);
    }

    /**
     * 初始化进入事件-告警关联页
     *
     * @param eventId
     * @return
     */
    @RequestMapping("/initEventAlerts")
    public ModelAndView initEventAlerts(Long eventId) {
        logger.debug(">>>>> 初始化进入事件-告警信息列表页 initEventAlerts() eventId:" + eventId);
        ModelAndView view = new ModelAndView(BASE_URL + "/event_alerts");
        try {
            EventVO event = indexEventService.getEventByEventIds(eventId + "").get(0);
            Set<Alert> alertList = event.getAlerts();
            view.addObject("alertList", AlertVO.getAlertVOs(alertList));
            view.addObject("event", EventVO.getEventVO(event));
        } catch (Exception e) {
            logger.error(" 初始化失败：" + e.getMessage(), e);
        }
        logger.debug("<<<<< 初始化进入事件-告警信息列表页 initEventAlerts() eventId:" + eventId);
        return view;
    }

    /**
     * 初始化进入编辑事件界面
     *
     * @param eventId
     * @return
     */
    @RequestMapping("/initEditEvent")
    public ModelAndView initEditEvent(Long eventId) {
        logger.debug(">>>>> 初始化进入编辑界面 initEditEvent() eventId:" + eventId);
        ModelAndView view = new ModelAndView(BASE_URL + "/event_edit");
        try {
            EventVO event = indexEventService.getEventByEventIds(eventId + "").get(0);
            view.addObject("event", EventVO.getEventVO(event));
            view.addObject("eventJson", JSONUtils.javaBean2Json(event));
        } catch (IOException e) {
            logger.error("初始化进入编辑界面异常:" + e.getMessage(), e);
        }
        logger.debug("<<<<< 初始化进入编辑界面 initEditEvent() eventId:" + eventId);
        return view;
    }

    /**
     * 保存编辑后的事件信息
     *
     * @param eventStr
     * @return
     */
    @ResponseBody
    @RequestMapping("/saveEventAfterEdit")
    public ModelMap saveEventAfterEdit(String eventStr) {
        logger.debug(">>>>> 保存编辑后的事件信息 saveEventAfterEdit()");
        try {
            EventVO event = JSONUtils.jsonStr2JavaBean(eventStr, EventVO.class);
            indexEventService.updateEvent(event);
        } catch (Exception e) {
            logger.error("保存出错：" + e.getMessage(), e);
            return JSONMapper.createReturnMap(SystemConstant.RESPONSE_CODE_FAILURE, "", null, null);
        }
        logger.debug("<<<<< 保存编辑后的事件信息 saveEventAfterEdit()");
        return JSONMapper.createReturnMap(SystemConstant.RESPONSE_CODE_SUCCESS, "", null, null);
    }

    /**
     * 通过事件id删除事件
     *
     * @param eventId
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteEvent")
    public ModelMap deleteEvent(Long eventId) {
        logger.debug(">>>>> 删除事件 deleteEvent() eventId:" + eventId);
        try {
            /**
             * 事件删除操作：
             * 1：更改事件删除标记为1
             * 2：解绑事件-告警关联关系
             */
            //1.
            Event event = new Event();
            event.setEventId(eventId);
            event.setDeleteFlag(1);


        } catch (Exception e) {
            logger.error("删除出错：" + e.getMessage(), e);
            return JSONMapper.createReturnMap(SystemConstant.RESPONSE_CODE_FAILURE, "", null, null);
        }
        logger.debug("<<<<< 删除事件 deleteEvent() eventId:" + eventId);
        return JSONMapper.createReturnMap(SystemConstant.RESPONSE_CODE_SUCCESS, "", null, null);
    }

    @ResponseBody
    @RequestMapping("/getEventById")
    public ModelMap getEventById(Long eventId) {
        logger.debug(">>>>> 获取单个告警 getEventById() eventId:" + eventId);
        EventVO event = null;
        try {
            event = indexEventService.getEventByEventIds(event + "").get(0);
        } catch (Exception e) {
            logger.error("获取单个告警出错:" + e.getMessage(), e);
            return JSONMapper.createReturnMap(SystemConstant.RESPONSE_CODE_FAILURE, "", null, null);
        }
        logger.debug("<<<<< 获取单个告警 getEventById() eventId:" + eventId);
        return JSONMapper.createReturnMap(SystemConstant.RESPONSE_CODE_SUCCESS, "", null, event);
    }

    @ResponseBody
    @RequestMapping("/getAlertsByEventId")
    public ModelMap getAlertsByEventId(String pageNo, String pageSize, Long eventId) {
        logger.debug(">>>>> 获取事件下的告警信息 getAlertsByEventId() evnetId=" + eventId);
        PageInfo<AlertVO> info = null;
        try {
            info = indexEventService.getAlertsInfoByEventId(pageNo, pageSize, eventId);
            List<AlertVO> list = info.getList();
            if (list != null) {
                for (AlertVO vo : list) {
                    vo.setAlertLevelInfo(AlertEnums.AlertLevelEnum.getLevelMsg(vo.getAlertLevel()));
                    vo.setAlertStateInfo(AlertEnums.AlertStateEnum.getStateMsg(vo.getAlertState()));
                    vo.setTriggerTimeStr(DateFormatUtils.date2Str(vo.getTriggerTime()));
                }
            }
        } catch (Exception e) {
            logger.error("获取告警信息出错：" + e.getMessage(), e);
            return JSONMapper.createReturnMap(SystemConstant.RESPONSE_CODE_FAILURE, "", null, null);
        }
        logger.debug("<<<<< 获取事件下的告警信息 getAlertsByEventId() evnetId=" + eventId);
        return PageData.getReturnMap(info);
    }


    @RequestMapping("/initCloseEvent")
    public ModelAndView initCloseEvent(Long eventId) {
        logger.debug(">>>>> 关闭事件 initCloseEvent() eventId:" + eventId);
        ModelAndView view = new ModelAndView(BASE_URL + "/event_close");
        try {
            EventVO event = indexEventService.getEventByEventIds(eventId + "").get(0);
            view.addObject("event", event);
        } catch (Exception e) {
            logger.error("事件关闭界面初始化异常：" + e.getMessage(), e);
        }
        view.addObject("eventId", eventId);
        logger.debug("<<<<< 关闭事件 initCloseEvent() eventId:" + eventId);
        return view;
    }


    /**
     * 关闭事件
     *
     * @param eventId
     */
    @ResponseBody
    @RequestMapping("/closeEvent")
    public ModelMap closeEvent(Long eventId, String email) {
        logger.debug(">>>>> 关闭事件 closeEvent() eventId:" + eventId);
        try {
            indexEventService.closeEvent(eventId, email);
        } catch (Exception e) {
            logger.error("关闭事件异常：" + e.getMessage(), e);
            return JSONMapper.createReturnMap(SystemConstant.RESPONSE_CODE_FAILURE, "", null, null);
        }
        logger.debug("<<<<< 关闭事件 closeEvent() eventId:" + eventId);
        return JSONMapper.createReturnMap(SystemConstant.RESPONSE_CODE_SUCCESS, "", null, null);
    }

}
